package com.example.vpnservicedemo;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.VpnService;
import android.os.ParcelFileDescriptor;

import java.io.IOException;

public class MyVpnService extends VpnService {

    private ParcelFileDescriptor descriptor;

    private PendingIntent pendingIntent;
    private ReadVpn readVpn;

    @Override
    public void onCreate() {

        super.onCreate();
        setupVpn();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String status = intent.getStringExtra("status");
        if("start".equals(status)){
            setupVpn();
        }else if("stop".equals(status)){
            stopVpn();
        }

        return START_STICKY;
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        stopVpn();
    }

    private void setupVpn() {

        if (descriptor == null) {
            Builder builder = new Builder();
            // 添加IPv4地址
            builder.addAddress("10.0.0.2", 32);
            // 添加IPv4路由,拦截所有ipv4
            builder.addRoute("0.0.0.0", 0);
            // 添加dns服务器
            builder.addDnsServer("114.114.114.114");
            try {
                //指定应用拦截
//                builder.addAllowedApplication("com.example.vpnservicedemo");
                builder.addAllowedApplication("com.android.browser");
            } catch (PackageManager.NameNotFoundException e) {
                throw new RuntimeException(e);
            }

            // ParcelFileDescriptor是一个文件描述符，它是一种程序读写已打开文件、socket的对象
            descriptor = builder.setConfigureIntent(pendingIntent).establish();

            //创建一个读取对象
            readVpn = new ReadVpn(this, descriptor);
            readVpn.start();

        }


    }

    private void stopVpn() {

        readVpn.stop();
        try {
            descriptor.close();
            descriptor = null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
